#define _CRT_SECURE_NO_WARNINGS
#include"stack.h"
int compare(const void* a, const void* b) {
    return (*(int*)b - *(int*)a);
}
MinStack* minStackCreate() {
    MinStack* new = malloc(sizeof(MinStack));
    int* a = malloc(4 * sizeof(int));
    int* b = malloc(4 * sizeof(int));
    new->a = a;
    new->top = 0;
    new->capacity = 4;
    new->min = b;
    return new;
}

void minStackPush(MinStack* obj, int x) {
    if (obj->top >= obj->capacity) {
        int* new = realloc(obj->a, obj->capacity * 2 * sizeof(int));
        int* y = realloc(obj->min, obj->capacity * 2 * sizeof(int));
        if (new == NULL) {
            printf("realloc failure\n");
            exit(-1);
        }
        else {
            obj->a = new;
            obj->min = y;
            obj->capacity *= 2;
        }
    }
    if (obj->top == 0)
        obj->min[obj->top] = x;
    else {
        obj->min[obj->top] = x;
        qsort(obj->min, obj->top+1, sizeof(int), compare);
    }
    obj->a[obj->top++] = x;

}
int* x(int* a,int x) {
    int* b = malloc(x*sizeof(int));
    for (int i = 0; i < x; i++) {
        b[i] = a[i];
    }
    qsort(b, x , sizeof(int), compare);
    return b;
}
void minStackPop(MinStack* obj) {
    assert(obj);
    assert(obj->top > 0);
    obj->top--;
    obj->min = x(obj->a,obj->top);
}

int minStackTop(MinStack* obj) {
    return obj->a[obj->top - 1];
}

int minStackGetMin(MinStack* obj) {
    return obj->min[obj->top - 1];
}

void minStackFree(MinStack* obj) {
    free(obj->a);
    free(obj);
    obj = NULL;
}